package org.example;

import org.apache.tomcat.websocket.WsWebSocketContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.socket.*;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;

import java.sql.Time;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

//@Component
public class WebSocketClient implements CommandLineRunner, WebSocketHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketClient.class);
    private static final AtomicLong counter = new AtomicLong();
    private static final AtomicLong clientNum = new AtomicLong();


    //项目启动，建立WebSocket连接
    @Override
    public void run(String... args) throws Exception {
        WsWebSocketContainer wsWebSocketContainer = new WsWebSocketContainer();
        wsWebSocketContainer.setDefaultMaxBinaryMessageBufferSize(5120000);
        wsWebSocketContainer.setDefaultMaxTextMessageBufferSize(5120000);
        StandardWebSocketClient client = new StandardWebSocketClient(wsWebSocketContainer);
        WebSocketHandler webSocketHandler = this;
        String uriTemplate = args[0];
        Object uriVars = null;
        ListenableFuture<WebSocketSession> future = client.doHandshake(webSocketHandler, uriTemplate, uriVars);
        try {
            WebSocketSession session = future.get();
            LOGGER.info("session={},clientNum={}", session, clientNum.incrementAndGet());
//            TimeUnit.SECONDS.sleep(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //建立连接后，执行的回调函数
    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
        String str8 = String.valueOf(clientNum.get());
        TextMessage message = new TextMessage(str8.getBytes());
        webSocketSession.sendMessage(message);
    }

    //解析服务端发送的消息
    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
        counter.incrementAndGet();
//        LOGGER.info(" client receive message:{} msgCounter={}", webSocketMessage.getPayload().toString(), counter.get());
        TextMessage msg = new TextMessage(("test msg_"+counter.get()).getBytes());
        webSocketSession.sendMessage(msg);
        TimeUnit.MILLISECONDS.sleep(500);
    }

    //异常回调函数
    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
        LOGGER.error("msg={},isOpen={},throwable={}",throwable.getMessage(),webSocketSession.isOpen(), throwable);
//        webSocketSession.close();

    }

    //连接关闭后回调函数，重连机制可以在这里实现
    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
        LOGGER.error("-------------ConnectionClosed {}", webSocketSession);
        webSocketSession.close();
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}

